package chapter3;

import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author caiya
 * @date 2020/3/25 20:00
 */
@Slf4j
public class CopyOnWriteArrayListTest {
    private static CopyOnWriteArrayList<String> copyOnWriteArrayList = new CopyOnWriteArrayList();

    public static void main(String[] args) throws InterruptedException {
        copyOnWriteArrayList.add("hello");
        copyOnWriteArrayList.add("world");
        copyOnWriteArrayList.add("welcome");
        copyOnWriteArrayList.add("to");
        copyOnWriteArrayList.add("xi'an");

        /**
         * CopyOnArrayList 是一个线程安全的list，具有弱一致性
         *
         * 何为弱一致性？
         *      当前线程返回迭代器后，其它线程再对List的操作对原先线程中的List是不可见的即无效的，因为重新复制了一份List
         *
         * 注意：必须在线程启动之前获取迭代器
         */
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                copyOnWriteArrayList.set(0, "haha");
                copyOnWriteArrayList.remove(2);
                copyOnWriteArrayList.remove(3);

                log.debug(Thread.currentThread().getName() + ": " + copyOnWriteArrayList.toString());
            }
        });

        // 必须在线程启动之前获取迭代器
        Iterator<String> iterator = copyOnWriteArrayList.iterator();

        thread.start();
        thread.join();

        while (iterator.hasNext()) {
            String next = iterator.next();
            log.debug(Thread.currentThread().getName() + ": " + next);
        }
    }
}
